﻿//  Symplectic Spark
//  Copyright 2010 Symplectic Ltd
//  Created by Martyn Whitwell (martyn@symplectic.co.uk)

//  This file is part of Spark.

//  Spark is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.

//  Spark is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with Spark.  If not, see <http://www.gnu.org/licenses/>.

// $URL: https://symplectic-spark.googlecode.com/svn/trunk/website/App_Code/Components.cs $
// $LastChangedDate: 2010-03-02 15:38:13 +0000 (Tue, 02 Mar 2010) $
// $LastChangedRevision: 11 $
// $LastChangedBy: martyn@symplectic.co.uk $

using System;
using System.Xml;
using System.IO;
using System.Xml.Linq;
using System.Collections.Generic;

using System.Diagnostics;

/// <summary>
/// Summary description for ElementTypes
/// </summary>

namespace Symplectic.Spark
{
    public class Components : Dictionary<string, Component>
    {
        public Components(XElement xComponents) : base(50)
        {

            string componentsDirectoryPathAbsolute = Path.GetDirectoryName(Global.ComponentsPathAbsolute);
            foreach (XElement xLoadComponent in xComponents.Elements("load"))
            {
                string source = xLoadComponent.Attribute("source").Value;
                string fileSpec = source.StartsWith(@"\") ?
                    Global.ApplicationPathAbsolute.TrimEnd(new char[] { '\\' }) + source : Path.Combine(componentsDirectoryPathAbsolute, source);

                foreach (string file in Directory.GetFiles(Path.GetDirectoryName(fileSpec), Path.GetFileName(fileSpec)))
                {
                    // Add the separate component files to the big components xml, so that 
                    // the hierarchy of attributes (e.g. Urls) are preserved
                    try
                    {
                        xComponents.Add(XElement.Load(file));
                    }
                    catch (XmlException ex)
                    {
                        throw new XmlException("Failed to parse file " + file, ex);
                    }
                }
            }

            //Now load each component
            foreach (XElement xComponent in xComponents.Elements("component"))
            {
                Component component = new Component(xComponent);
                this.Add(component.Name, component);
            }
        }
    }
}